import psutil
import socket

'''
def get_network_interfaces():
    interfaces = psutil.net_if_addrs()
    for interface_name, interface_addresses in interfaces.items():
        print(f"Interface: {interface_name}")
        for address in interface_addresses:
            if str(address.family) == 'AddressFamily.AF_INET':
                print(f"  IP Address: {address.address}")
                print(f"  Netmask: {address.netmask}")
                print(f"  Broadcast IP: {address.broadcast}")
            elif str(address.family) == 'AddressFamily.AF_PACKET':
                print(f"  MAC Address: {address.address}")
                print(f"  Netmask: {address.netmask}")
                print(f"  Broadcast MAC: {address.broadcast}")
        print()
 '''


def get_all_ipv4_addresses():
    addrs = psutil.net_if_addrs()
    ipv4_addrs = {}

    for interface, addr_list in addrs.items():
        for addr in addr_list:
            if addr.family == socket.AF_INET:  # AF_INET 表示 IPv4
                ipv4_addrs.setdefault(interface, []).append(addr.address)

    return ipv4_addrs


def get_local_ip():
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    print("Local IP Address:", local_ip)
    return local_ip

def get_local_ip_by_connection():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # 不需要实际发送数据，只需要创建一个 UDP 包
        s.connect(("8.8.8.8", 80))  # Google 的公共 DNS 服务器
        local_ip = s.getsockname()[0]
        print("Local IP Address by connection:", local_ip)          
    finally:
        s.close()

    return local_ip

 


if __name__ == '__main__':
    #get_network_interfaces()
    ipv4_addrs = get_all_ipv4_addresses()
    for interface, addrs in ipv4_addrs.items():
        print(f"Interface {interface}:")
        for addr in addrs:
            print(f"  - {addr}")

    get_local_ip()
    get_local_ip_by_connection()